<template>
  <div>
    <el-upload
      list-type="picture-card"
      :file-list="fileList"
      action="#"
      :class="{active:fileList.length>0}"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="newUpload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showProgress" style="width:146px" :text-inside="true" :stroke-width="26" :percentage="percentage" />
    <el-dialog title="图片预览" :visible="showDialog" @close="showDialog=false">
      <img :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
// 引入
import COS from 'cos-js-sdk-v5'
// 实例化
const cos = new COS({
  SecretId: 'AKIDe7KHxMddMozuYv1rQijTw83h5CQP8alf',
  SecretKey: 'e29zYqrb4GBpCI8hz0kDPKzNTIq77qIT'
})
export default {
  data() {
    return {
      fileList: [
      ],
      imgUrl: '',
      showDialog: false,
      percentage: 0,
      showProgress: false
    }
  },
  methods: {
    onPreview(file) {
      // console.log(file)
      this.imgUrl = file.url
      this.showDialog = true
    },
    onRemove(file, newFileList) {
      this.fileList = newFileList
    },
    onChange(file, newFileList) {
      this.fileList = newFileList
    },
    beforeUpload(file) {
      this.showProgress = true
      if (file.size > 2 * 1024 * 1024 * 1024) {
        this.$message.warning('文件大小不能超过2G')
        return false
      }
      const whilteList = ['image/jpeg', 'image/png', 'image/jpg']
      if (!whilteList.includes(file.type)) {
        this.$message.warning('图片格式错误')
        return false
      }
    },
    newUpload(params) {
      // console.log('上传中', params)
      cos.putObject({
        Bucket: 'hy-1307304499', // 存储桶
        Region: 'ap-nanjing', // 地域
        Key: params.file.name, // 文件名
        Body: params.file, // 要上传的文件对象
        StorageClass: 'STANDARD', // 上传的模式类型 直接默认 标准模式即可
        // 上传到腾讯云 =》 哪个存储桶 哪个地域的存储桶 文件  格式  名称 回调
        onProgress: (progressData) => {
          // console.log(75, JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        // data返回数据之后 应该如何处理
        // console.log(err || data)
        if (!err) {
          this.fileList[0].url = 'http://' + data.Location
          this.fileList[0].status = 'success'
        }
        setTimeout(() => {
          this.showProgress = false
        }, 1000)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.active{
  ::v-deep.el-upload--picture-card{
    display:none
  }
}
img{
    width: 100%;
  }
</style>
